/**
 * 
 */
package org.rico.news.filter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.rico.sso.commons.HttpClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 登录回调操作
 * @author rico
 *
 */
public class LoginCallbackHandler extends HttpServlet {
	private static final Logger logger = LoggerFactory.getLogger(LoginCallbackHandler.class);
	
	/* (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.doPost(req, resp);
	}
	
	/* (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// sso认证中心登录后，跳转回子系统并附上令牌，子系统（sso-client）取得令牌，
		// 然后去sso认证中心校验，在LoginFilter.java的doFilter()中添加几行
		String token = req.getParameter("token");
		logger.info("LoginCallbackHandler.token= {}", token);
		
		if(token==null || "".equals(token)) {
			resp.sendRedirect("http://localhost:8080/sso/login.jsp?backUrl=http://localhost:8081/news/loginCallback");

		} else {
			//TODO sso认证中心校验
			boolean result = this.validateToken(token, "news");
			if(!result) {
				resp.sendRedirect("http://localhost:8080/sso/login.jsp?backUrl=http://localhost:8081/news/loginCallback");
			}
			
			req.getSession().setAttribute("isLogin", true);
			req.getSession().setAttribute("token", token);
			resp.sendRedirect("http://localhost:8081/news/home");
		}
	}
	
	/**
	 * 检验token的有效性
	 * @param token
	 * @return
	 * @throws IOException 
	 */
	private boolean validateToken(String token, String systemId) throws IOException {
		Map<String, String> params = new HashMap<>();
		params.put("systemId", systemId);
		params.put("token", token);
		String result = HttpClientUtil.httpPost("http://localhost:8080/sso/tokenValidate", params);
		if("true".equals(result)) {
			return true;
		}
		
		return false;
	}
}
